package com.duolaibei.pay.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.duolaibei.pay.R;
import com.duolaibei.pay.adapter.PayAdapter;
import com.duolaibei.pay.base.BaseActivity;
import com.duolaibei.pay.base.MyApplication;
import com.duolaibei.pay.bean.PayOrder;
import com.duolaibei.pay.http.BaseCallback;
import com.duolaibei.pay.http.ParamsUtils;
import com.duolaibei.pay.http.Result;
import com.duolaibei.pay.http.api.ApiName;
import com.duolaibei.pay.smprint.AidlUtil;
import com.duolaibei.pay.utils.SharedPreferencesUtils;
import com.duolaibei.pay.utils.TimeUtils;
import com.duolaibei.pay.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by wangshuo on 2017/5/26.
 */

public class SearchResultAtivity extends BaseActivity implements BaseCallback<Result<Map<String, Object>>> {

    @Bind(R.id.pay_money_sum)
    TextView payMoneySum;
    @Bind(R.id.pay_count)
    TextView payCount;
    @Bind(R.id.print)
    TextView print;
    @Bind(R.id.detail_list)
    ListView detailList;
    @Bind(R.id.start_time)
    TextView start;
    @Bind(R.id.endtimes)
    TextView endtimes;
    @Bind(R.id.title_ll)
    LinearLayout titleLl;
    private int pageIndex = 1;
    private int pageNum = 10;
    private String startTime = "";
    private String endTime = "";
    private String payStatus = "";
    private PayAdapter adapter;
    private List<PayOrder> list;
    private Calendar c = Calendar.getInstance();
    private String sumMoney;
    private String count;
    private String refundMoney;//退款金额
    //如果没有传开始／结束时间。则使用默认时间
    String default_startTime;
    String default_endTime;
    private int indexType = 0;
    private static final String PAY_TYPE = "22";// 刷卡类型

    @Override
    public int getContentViewResId() {
        return R.layout.activity_search_result;
    }

    @Override
    public void intiViews() {
        adapter = new PayAdapter(this);
        detailList.setAdapter(adapter);
        detailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(SearchResultAtivity.this, DealDetailsActivity.class);
                PayOrder po = (PayOrder) adapter.getItem(i);
                intent.putExtra("order", po);
                startActivity(intent);
            }
        });
        detailList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (absListView.getCount() < pageNum) {
                    return;
                }

                // 当不滚动时
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        if (indexType == BrushCardManagerActivity.INDEX_TYPE) {
                            getBrushAllOrder();
                        } else {
                            request();
                        }
                    }
                }

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
        Intent intent = getIntent();
        if (null != intent) {
            startTime = intent.getStringExtra("startTime");
            endTime = intent.getStringExtra("endTime");
            payStatus = intent.getStringExtra("status");
            indexType = intent.getIntExtra("pay_type", 0);
            if (payStatus == null) {
                payStatus = "1";
            }
            String month = ((c.get(Calendar.MONTH) + 1) < 10 ? "0" + (c.get(Calendar.MONTH) + 1) : (c.get(Calendar.MONTH) + 1)) + "";
            String day = c.get(Calendar.DATE) < 10 ? "0" + c.get(Calendar.DATE) : c.get(Calendar.DATE) + "";
            default_startTime = c.get(Calendar.YEAR) + "-" + month + "-" + day + " " + "00:00:00";
            default_endTime = c.get(Calendar.YEAR) + "-" + month + "-" + day + " " + c.get(Calendar.HOUR_OF_DAY) + ":" + (c.get(Calendar.MINUTE) < 10 ? "0" + c.get(Calendar.MINUTE) : c.get(Calendar.MINUTE)) + ":" + (c.get(Calendar.SECOND) < 10 ? "0" + c.get(Calendar.SECOND) : c.get(Calendar.SECOND));
            start.setText(startTime == null ? default_startTime : startTime);
            endtimes.setText(endTime == null ? default_endTime : endTime);
        }

        if (startTime != null && endTime != null) {
        }
        print.setOnClickListener(this);

        //网络请求
        if (indexType == BrushCardManagerActivity.INDEX_TYPE) {
            getBrushAllOrder();
        } else {
            request();
        }

    }

    protected void request() {
        MyApplication.getSerivceApi().getAllOrder(SharedPreferencesUtils.getAppid(),
                ApiName.GET_ALL_ORDER, ParamsUtils.getAllOrder(startTime, endTime, pageIndex + "", pageNum + "", payStatus, ""), SharedPreferencesUtils.getTerminalNumber(), SharedPreferencesUtils.getWorkMenId(),
                startTime, endTime, pageIndex + "", pageNum + "", payStatus).enqueue(SearchResultAtivity.this);
    }

    /**
     * 查询刷卡明细的请求
     */
    private void getBrushAllOrder() {
        MyApplication.getSerivceApi().getBrushAllOrder(SharedPreferencesUtils.getAppid(),
                ApiName.GET_ALL_ORDER, ParamsUtils.getAllOrder(startTime, endTime, pageIndex + "", pageNum + "", "1", PAY_TYPE), SharedPreferencesUtils.getTerminalNumber(), SharedPreferencesUtils.getWorkMenId(),
                startTime, endTime, pageIndex + "", pageNum + "", "1", PAY_TYPE).enqueue(this);
    }

    @Override
    public String setTitle() {
        return "统计查询";
    }

    @Override
    public void onResponse(Call<Result<Map<String, Object>>> call, Response<Result<Map<String, Object>>> response) {
        if (response.code() == 200) {
            if (response.body().getStatus().equals("1")) {
                List<Map<String, String>> payOrders = (List<Map<String, String>>) response.body().getResult().get("list");
                if (null == payOrders || payOrders.size() == 0) {
                    ToastUtils.showToast(SearchResultAtivity.this, "没有数据", 3000);
                    return;
                }
                list = mapToPayorder(payOrders);
                adapter.setData(list);
                sumMoney = response.body().getResult().get("count_total_amount").toString();
                count = response.body().getResult().get("count_order").toString();
                refundMoney = response.body().getResult().get("count_discountable_amount").toString();
                if (!refundMoney.equals("0.00")) {
                    payMoneySum.setText(getString(R.string.today_deal_sum, refundMoney));
                } else {
                    payMoneySum.setText(getString(R.string.today_deal_sum, sumMoney));
                }
                payCount.setText(getString(R.string.today_deal_count, ((int) Double.parseDouble(count)) + ""));
                pageIndex++;
            }
        }
    }

    private List<PayOrder> mapToPayorder(List<Map<String, String>> data) {
        List<PayOrder> list = new ArrayList<>();
        int length = data.size();
        PayOrder po = null;
        for (int i = 0; i < length; i++) {
            po = new PayOrder();
            po.setOut_trade_no(data.get(i).get("out_trade_no"));
            po.setBody(data.get(i).get("body"));
            po.setUid(data.get(i).get("uid"));
            po.setTrade_no(data.get(i).get("trade_no"));
            po.setService(data.get(i).get("service"));
            po.setProduct_id(data.get(i).get("product_id"));
            po.setPay_type(data.get(i).get("pay_type"));
            po.setTotal_amount(data.get(i).get("total_amount"));
            po.setDiscountable_amount(data.get(i).get("discountable_amount"));
            po.setPay_amount(data.get(i).get("pay_amount"));
            po.setUid(data.get(i).get("pay_uid"));
            po.setShop_id(data.get(i).get("shop_id"));
            po.setTerminal_id(data.get(i).get("terminal_id"));
            po.setAgent_uid(data.get(i).get("agent_uid"));
            po.setWorkmen_id(data.get(i).get("workmen_uid"));
            po.setStatus(data.get(i).get("status"));
            po.setPaytime(data.get(i).get("paytime"));
            po.setAddtime(data.get(i).get("addtime"));
            po.setUptime(data.get(i).get("uptime"));
            po.setPay_name(data.get(i).get("pay_name"));
            list.add(po);
        }
        return list;
    }

    @Override
    public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
        Log.v("onFailure", "error messgar :" + t.getMessage());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        if (id == R.id.print) {
            //打印
            smPrint();
        }
    }

    /**
     * 商米打印
     */
    private void smPrint() {
        if (null == list || list.size() == 0) {
            ToastUtils.showToast(this, getString(R.string.no_have_data), 3000);
            return;
        }
        TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        String month = ((c.get(Calendar.MONTH) + 1) < 10 ? "0" + (c.get(Calendar.MONTH) + 1) : (c.get(Calendar.MONTH) + 1)) + "";
        String day = c.get(Calendar.DATE) < 10 ? "0" + c.get(Calendar.DATE) : c.get(Calendar.DATE) + "";
        //初始化打印服务
        if (AidlUtil.getInstance().isConnect()) {
            AidlUtil.getInstance().initPrinter();
        }
        //标题
        AidlUtil.getInstance().printText(getString(R.string.today_count_orders) + "\n\n", 30, 1);
        //开始时间
        AidlUtil.getInstance().printText(getString(R.string.start_time) + (startTime == null ? default_startTime : startTime) + "\n");
        //结束时间
        AidlUtil.getInstance().printText(getString(R.string.end_time) + (endTime == null ? default_endTime : endTime) + "\n");
        //交易描述
        AidlUtil.getInstance().printText(getString(R.string.pay_describe, list.get(0).getBody()) + "\n");
        //终端编号
        AidlUtil.getInstance().printText(getString(R.string.terminal_num, SharedPreferencesUtils.getTerminalNumber()) + "\n");
        //订单编号
        AidlUtil.getInstance().printText(getString(R.string.device_num, tm.getDeviceId()) + "\n");
        AidlUtil.getInstance().printText("-----------------------------" + "\n");
        if (payStatus.equals("1")) {
            // 收款
            AidlUtil.getInstance().printText(getString(R.string.gathering) + "\n", 30, 1);
        } else if (payStatus.equals("-1")) {
            // 退款
            AidlUtil.getInstance().printText(getString(R.string.refund) + "\n", 30, 1);
        }
        //笔数
        AidlUtil.getInstance().printText(getString(R.string.count, ((int) Double.parseDouble(count)) + "") + "\n");
        //金额
        AidlUtil.getInstance().printText(getString(R.string.money, sumMoney) + "\n");
        //打印时间
        AidlUtil.getInstance().printText(getString(R.string.print_time) + "\t" + c.get(Calendar.YEAR) + "-" + month + "-" + day + " " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + "\n");
        //空打五行
        AidlUtil.getInstance().print5Line();
    }
}
